<template>
  <div class="root">
    <div class="title-box" v-if="!hasAccident">
      <div class="title-text-common title-text">日常值守</div>
    </div>
    <template v-else>
      <div class="title-box">
        <div class="title-text-common title-text" style="font-size: 40px;">应急指挥调度平台</div>
      </div>
      <div class="top-btn position2">
        <div class="title-text-common" @click="rescueShow()">救援力量</div>
      </div>
      <div class="top-btn position1">
        <div class="title-text-common" @click="groupShow()">应急专家</div>
      </div>
      <div class="top-btn position3">
        <div class="title-text-common" @click="ashow()">警情描述</div>
      </div>
      <div class="top-btn position4">
        <div class="title-text-common" @click="videoShow()">现场视频</div>
      </div>
    </template>

    <transition name="el-zoom-in-top">
      <!-- 用:key强制组件刷新 -->
      <panel1 v-show="shows.show1" :key="groupKey" />
    </transition>

    <transition name="el-zoom-in-bottom">
      <AccidentPanel v-show="shows.show2" :key="akey" />
    </transition>

    <transition name="el-zoom-in-top">
      <panel3 v-show="shows.show3" @transfer="getPosition" />
    </transition>
    <transition name="el-zoom-in-bottom">
      <panel4 v-show="shows.show4" />
    </transition>
    <div id="map"></div>
  </div>
</template>
    
  <script>
import AMapLoader from "@amap/amap-jsapi-loader";
import panel1 from "./components/panel1";
import AccidentPanel from "./components/AccidentPanel";
import panel3 from "./components/panel3";
import panel4 from "./components/panel4";
import { getLatestAccident } from "@/api/accidenthandle/accident";
import { ListRecureTeam } from "@/api/accidenthandle/panel3";
import { getRescueRequest } from "../../../api/accidenthandle";
//设置密钥
window._AMapSecurityConfig = {
  securityJsCode: "7559c249fc70306556c2dae399c37bee",
};
//导出组件
export default {
  name: "MapContainer",
  data() {
    return {
      AMap: {},
      akey: 0,
      groupKey: 0,
      shows: {
        show1: false,
        show2: false,
        show3: false,
        show4: false,
        teamList: [],
      },
      hasAccident: false,
      map: {},
      xf: [], //应急救护队
      yl: [], //应急消防队
      tx: [], //通信保障类
      hxp: [], //危险化学品类
      hj: [], //环境应急救援队
      shelter: [], //避难场所
      wz: [], //应急物资
      timer: {}, //用于获取事件的计时器
      accidentPlace: {}, //保存事故地点的经纬度
      position: [], //用于路径规划的地址列表
      timer1:{}//用于获取请求撤离的timer;
    };
  },
  methods: {
    //初始化地图
    initMap(longitude, latitude) {
      var aid = this.$store.state.accidentHandle.accindentId;
      AMapLoader.load({
        key: "	3dd5779e61694ff455f750c27ff865d7", //申请好的Web端开发者Key，首次调用 load 时必填
        version: "2.0", // 指定要加载的 JSAPI 的版本，缺省时默认为 1.4.15
        plugins: [""], // 需要使用的的插件列表，如比例尺'AMap.Scale'等w
      })
        .then((AMap) => {
          this.AMap = AMap;
          this.map = new AMap.Map("map", {
            //设置地图容器id
            viewMode: "3D", //是否为3D地图模式
            zoom: aid == -1 ? 12 : 15, //初始化地图级别
            center: [longitude, latitude], //初始化地图中心点位置
            // mapStyle: "amap://styles/darkblue"
          });
          if (aid != -1) {
            //在地图上添加事件地点
            this.initTeamMarkerPoints();
            this.addAccidentMarker(longitude, latitude);
          }
        })
        .catch((e) => {
          console.log(e);
        });
    },
    //控制accident面板显示
    ashow() {
      this.shows.show2 = !this.shows.show2;
      if (this.shows.show2 == true) {
        this.akey += 1;
      }
    },
    //控制救援力量显示面板
    rescueShow() {
      this.shows.show3 = !this.shows.show3;
    },
    //专家组面板show
    groupShow() {
      this.shows.show1 = !this.shows.show1;
      if (this.shows.show2 == true) {
        this.groupKey += 1;
      }
    },
    //视频面板show
    videoShow() {
      this.shows.show4 = !this.shows.show4;
    },
    //切换到指挥状态,同时开启请求救援监听计时器
    changeMode() {
      this.hasAccident = true;
      this.ashow();
      this.rescueShow();
      this.groupShow();
      this.videoShow();
      this.timer1 = setInterval(() => {
        this.getRequest();
      }, 1000);
    },
    //查询请求
    getRequest(){
      var id =this.$store.state.accidentHandle.accindentId;
      getRescueRequest(id).then((res)=>{
        if(res.code==200){
          //如果查到则结束定时器
          clearInterval(this.timer1);
          if(res.data.type==1){
            var title = "请求增援提示";
            var message = '现场救援队请求增援';
          }
          if(res.data.type==2){
            var title = "请求撤离提示";
            var message = '现场救援队请求撤离';
          }
                  
          this.$notify({
            title: title,
            message: message,
            duration: 0,
            type: 'warning'
          });
        }
      })
    },
    clearTeams() {
      this.xf = []; //应急救护队
      this.yl = []; //应急消防队
      this.tx = []; //通信保障类
      this.hxp = []; //危险化学品类
      this.hj = []; //环境应急救援队
    },
    initTeamMarkerPoints() {
      ListRecureTeam().then((res) => {
        if (res.code == 200) {
          this.clearTeams();
          for (var item of res.data) {
            console.log(item);
            var img;
           
            switch (item.typeCode) {
              case 1:
                img = require("../../../assets/images/accidentHandle/yl.svg");
                break;
              case 2:
                img = require("../../../assets/images/accidentHandle/xf.svg");
                break;
              case 3:
                img = require("../../../assets/images/accidentHandle/tx.svg");
                break;
              case 4:
                img = require("../../../assets/images/accidentHandle/hxp.svg");
                break;
              case 5:
                img = require("../../../assets/images/accidentHandle/hj.svg");
                break;
              default:
            }
            this.addTeamMarker(
              item.longitude,
              item.latitude,
              item.teamName,
              img
            );
          }
        }
      });
    },
    initAccident() {
      getLatestAccident().then((res) => {
        //获取成功
        if (res.code == 200) {
          clearInterval(this.timer);
          this.$alert("有一个新的应急事件,进入应急指挥模式", "提示", {
            confirmButtonText: "确定",
            callback: (action) => {
              var value = parseInt(res.data.id);
              this.$store.dispatch("getId", value);
              //如果当前还没有事件
              if (!this.hasAccident) {
                //加载
                const loading = this.$loading({
                  lock: true,
                  text: "Loading",
                  spinner: "el-icon-loading",
                  background: "rgba(0, 0, 0, 0.7)",
                });
                this.changeMode();
                //登记位置
                this.accidentPlace = {
                  longitude: res.data.longitude,
                  latitude: res.data.latitude,
                };
                this.initMap(res.data.longitude, res.data.latitude);
                //取消加载
                loading.close();
              }
            },
          });
        } else if (res.code == 201) {
        }
      });
    },
    addAccidentMarker(longitude, latitude) {
      var marker = new AMap.Marker({
        position: new AMap.LngLat(longitude, latitude),
        // offset: new AMap.Pixel(-10, -10),
        icon: new AMap.Icon({
          image: require("../../../assets/images/accidentHandle/accident.png"),
          // size: new AMap.Size(50, 50), //图标大小
          // imageSize: new AMap.Size(50, 50),
        }),
        title: "北京",
      });
      this.map.add(marker); //添加到地图
    },
    addTeamMarker(longitude,latitude,name,img) {
      console.log(longitude,latitude);
      var marker = new this.AMap.Marker({
        position: new this.AMap.LngLat(longitude, latitude),
        // offset: new AMap.Pixel(-10, -10),
        icon: new this.AMap.Icon({
          image: img,
          size: new this.AMap.Size(40, 40), //图标大小
          imageSize: new this.AMap.Size(40, 40),
        }),
        title: name,
      });
      this.map.add(marker); //添加到地图
    },
    //接收子组件上传的地址信息
    getPosition(msg) {
      this.position.push(msg);
    },
    //路径规划
    path() {
      this.AMap.plugin("AMap.Driving", () => {
        var drivingOption = {
          policy: this.AMap.DrivingPolicy.LEAST_TIME,
          province: "京", // 车牌省份的汉字缩写
        };

        // 构造路线导航类
        var driving = new this.AMap.Driving(drivingOption);

        // 根据起终点经纬度规划驾车导航路线
        console.log(this.accidentPlace.longitude, this.accidentPlace.latitude);
        driving.search(
          //起点
          new this.AMap.LngLat(
            this.position[this.position.length - 1].longitude,
            this.position[this.position.length - 1].latitude
          ),
          //终点
          new this.AMap.LngLat(
            this.accidentPlace.longitude,
            this.accidentPlace.latitude
          ),
          (status, result) => {
            // result即是对应的驾车导航信息，相关数据结构文档请参考 https://lbs.amap.com/api/javascript-api/reference/route-search#m_DrivingResult
            if (status === "complete") {
              if (result.routes && result.routes.length) {
                // 绘制第一条路线，也可以按需求绘制其它几条路线
                this.drawRoute(result.routes[0]);
              }
            } else {
            }
          }
        );
      });
    },
    //绘制路径调用方法
    drawRoute(route) {
      var path = this.parseRouteToPath(route);

      var startMarker = new this.AMap.Marker({
        position: path[0],
        icon: "https://webapi.amap.com/theme/v1.3/markers/n/start.png",
        map: this.map,
      });

      var endMarker = new this.AMap.Marker({
        position: path[path.length - 1],
        icon: "https://webapi.amap.com/theme/v1.3/markers/n/end.png",
        map: this.map,
      });
      var routeLine = new this.AMap.Polyline({
        path: path,
        isOutline: true,
        outlineColor: "#ffeeee",
        borderWeight: 2,
        strokeWeight: 5,
        strokeOpacity: 0.9,
        strokeColor: "#0091ff",
        lineJoin: "round",
      });

      this.map.add(routeLine);

      // 调整视野达到最佳显示区域
      this.map.setFitView([startMarker, endMarker, routeLine]);
    },
    // 解析DrivingRoute对象，构造成AMap.Polyline的path参数需要的格式
    // DrivingResult对象结构参考文档 https://lbs.amap.com/api/javascript-api/reference/route-search#m_DriveRoute
    parseRouteToPath(route) {
      var path = [];

      for (var i = 0, l = route.steps.length; i < l; i++) {
        var step = route.steps[i];

        for (var j = 0, n = step.path.length; j < n; j++) {
          path.push(step.path[j]);
        }
      }

      return path;
    },
  },
  components: {
    panel1,
    AccidentPanel,
    panel3,
    panel4,
  },
  watch: {
    position: function (val, oldVal) {
      this.path();
    },
  },
  mounted() {
    // 初始化地图 
    this.initMap(119.178821, 34.600018);
    this.initTeamMarkerPoints();
    console.log("mounted调用");
    //如果还没初始化过事件
    if (this.$store.state.accidentHandle.accindentId == -1) {
      //立即执行一次，然后美五秒钟执行一次
      this.timer = setInterval(() => {
        this.initAccident();
      }, 1000);
    } else {
      this.changeMode();
    }
  },
  destroyed() {
    clearInterval(this.timer);
  },
};
</script>
    
  <style scoped>
#root {
  height: 100%;
  width: 100%;
  position: relative;
}
.title-box {
  /*文字居中*/
  width: 500px;
  height: 80px;
  display: flex;
  justify-content: center;
  align-items: center;
  /*子内容绝对定位*/
  position: absolute;
  left: 50%;
  z-index: 1;
  user-select: none;
  margin-left: -250px;
  background-color: rgba(75, 87, 89, 0.85);
  border-radius: 5px;
}
.title-text {
  font-size: 40px;
}
.title-text-common {
  color: white;
  font-size: 25px;
  font-weight: bold;
}
.top-btn {
  width: 170px;
  height: 32px;
  position: absolute;
  top: 30px;
  z-index: 1;
  display: flex;
  justify-content: center;
  align-items: center;
  user-select: none;
  background-color: #606266;
  opacity: 0.9;
}
.top-btn :hover {
  width: 170px;
  height: 32px;
  display: flex;
  justify-content: center;
  align-items: center;
  user-select: none;
  background-color: #000000;
}
.position1 {
  left: 10px;
}
.position2 {
  left: 350px;
}
.position3 {
  right: 350px;
}
.position4 {
  right: 10px;
}

#map {
  padding: 0px;
  margin: 0px;
  width: 100vw;
  /* height: 91vh; */
  height: 100vh;
}
</style>
    
  